﻿/*-----------------------------------------------------------------------
 * <copyright file="Command.Loaded.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Li Dawei&Zhang Jun</author>
 * <summary>
 *          滚轮事件(整个控件或页面)
 *          http://blog.csdn.net/soft2buy/archive/2010/09/16/5888600.aspx
 *          作成日： 10/11/2010 
 *
 * </summary>
 *-----------------------------------------------------------------------
 */

using System.Windows;
using System.Windows.Input;

namespace WSick.Client.Extensions
{
    public partial class Command
    {
        public static readonly DependencyProperty LoadedCommandProperty = DependencyProperty.RegisterAttached(
            "LoadedCommand", typeof(ICommand), typeof(Command), new PropertyMetadata(OnLoadedCommandPropertyChanged));

        public static readonly DependencyProperty LoadedCommandParameterProperty = DependencyProperty.RegisterAttached(
            "LoadedCommandParameter", typeof(ICommand), typeof(Command), new PropertyMetadata(null));

        public static ICommand GetLoadedCommand(object d)
        {
            if (d is DependencyObject)
                return (ICommand)(d as DependencyObject).GetValue(LoadedCommandProperty);
            return null;
        }

        public static object GetLoadedCommandParameter(object d)
        {
            if (d is DependencyObject)
                return (d as DependencyObject).GetValue(LoadedCommandParameterProperty);
            return null;
        }

        private static void OnLoadedCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is FrameworkElement)
            {
                if (e.OldValue == null && e.NewValue != null)
                {
                    (d as FrameworkElement).Loaded += Command_Loaded;
                }
                else if (e.OldValue != null && e.NewValue == null)
                {
                    (d as FrameworkElement).Loaded -= Command_Loaded;
                }
            }
        }

        private static void Command_Loaded(object sender, RoutedEventArgs e)
        {
            if (sender is FrameworkElement)
            {
                ICommand cmd = GetLoadedCommand(sender);
                object param = GetLoadedCommandParameter(sender);
                if (cmd.CanExecute(param))
                    cmd.Execute(param);
            }
        }
    }
}
